<template>
  <div class="waikuang">
    <div class="chatKuang">
      <div class="msg" v-for="(item, index) in msgList" :key="index">
        {{ item.msg }}
      </div>
    </div>
    <textarea
      @keydown.enter="enterSet"
      class="textarea"
      v-model="textarea"
    ></textarea>
    <div @click="sendClick" class="send">
      <i class="el-icon-s-promotion iconSend"></i>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from "@vue/runtime-core";
import { getToken } from "@/utils/token";
import { useStore } from "vuex";
export default {
  setup() {
    const data = reactive({
      textarea: "",
      msgList: [],
    });
    const store = useStore();

    function sendClick() {
      if (data.textarea) {
        sendMsg(data.textarea);
        data.msgList.push({
          msg: data.textarea,
        });
      }
      data.textarea = "";
    }
    function enterSet(e) {
      if (13 == e.keyCode && e.shiftKey) {
        console.log(e);
      } else {
        e.preventDefault();
        sendClick();
      }
    }
    function sendMsg(msg) {
      let websocket = store.state.websocket;
      if (websocket) {
        var msgData = {
          token: getToken(),
          msg: msg,
          time: new Date().getTime(),
        };
        websocket.ws.send(JSON.stringify(msgData));
      }
    }
    onMounted(() => {
      let websocket = store.state.websocket;
      if (websocket) {
        websocket.ws.onmessage = (message) => {
          var msg = JSON.parse(message.data);
          data.msgList.push(msg);
        };
      }
    });
    return { ...toRefs(data), sendClick, enterSet };
  },
};
</script>

<style lang="scss" scoped>
.waikuang {
  width: 1000px;
  margin: 0 auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  position: relative;
  .send {
    cursor: pointer;
    position: absolute;
    right: 15px;
    bottom: 15px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #3598db;
    text-align: center;
    .iconSend {
      line-height: 50px;
      font-size: 25px;
      color: white;
    }
  }
}
.chatKuang {
  height: 400px;
  overflow: auto;
  box-sizing: border-box;
  padding: 10px;
  .msg {
    position: relative;
    max-width: 450px;
    border-radius: 5px;
    background-color: #3598db;
    color: white;
    padding: 10px;
    word-break: break-all;
    &:before {
      position: absolute;
      left: -2px;
      top: 11px;
      transform: rotate(45deg);
      z-index: 0;
      content: "";
      width: 10px;
      height: 10px;
      background-color: #3598db;
    }
    &:not(:first-child) {
      margin-top: 10px;
    }
  }
}
.textarea {
  border: none;
  border-top: 1px solid #ccc;
  box-sizing: border-box;
  width: 100%;
  height: 120px;
  padding: 10px;
  resize: none;
  font-size: 15px;
  outline: none;
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #cccccc;
  }
}
</style>
